﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using CommunergyLogic;
using System.Data.Linq;
using System.Data;
using System.Web.UI.DataVisualization.Charting;
using Communergy.Repository;
using Communergy.Repository.EntityFramework;

namespace CommunergyWebApplication.Groups
{
    public partial class GroupDetails : System.Web.UI.Page
    {

        communergyEntities db = new communergyEntities();
        protected void Page_Load(object sender, EventArgs e)
        {

            var groupIdString = Request.QueryString["groupId"];
            var thisGroup = Helpers.GetGroupIfBelongsToUser(db, groupIdString);
            if (thisGroup != null)
            {


                var meters = (from gm in db.GroupMeter.Include("ElectricityMeter")
                              where gm.Group.gp_id == thisGroup.gp_id
                              select gm.ElectricityMeter).ToList();


                dgMetersForGroups.DataSource = meters;
                dgMetersForGroups.DataBind();


                var legendName = "MeterLegend";

                foreach (var meter in meters)
                {
                    //get the meter Name
                    var seriesName = meter.me_meterName;
                    
                    //sum the joules, grouped by year, month, day, hour
                    var meterData =( from er in db.ElectricityRealtime
                                    where er.ElectricityMeter.me_id == meter.me_id
                                    //create anon object for grouping
                                    group er.cc_joules by new 
                                    {                                        
                                        er.cc_dateTime.Year,
                                        er.cc_dateTime.Month,
                                        er.cc_dateTime.Day,
                                        er.cc_dateTime.Hour,
                                        er.cc_joules
                                    }
                                    into groupedData
                                    //sort
                                    orderby groupedData.Key.Year, groupedData.Key.Month, groupedData.Key.Day, groupedData.Key.Hour
                                    //project into object
                                    select new
                                    {                                       
                                        Year = groupedData.Key.Year,
                                        Month = groupedData.Key.Month,
                                        Day = groupedData.Key.Day,
                                        Hour =  groupedData.Key.Hour,
                                        Records = groupedData.Count(),
                                        TotalKWh = (decimal)groupedData.Sum() / 3600000

                                    }).ToList();
                    //project from database - can't create new date object in database
                    var data = from d in meterData
                               select new
                               {
                                   HourDate = new DateTime(d.Year, d.Month, d.Day, d.Hour, 0, 0),
                                   TotalKWh = d.TotalKWh
                               };
                    //add to series
                    Series series = chartGroupMetersHourly.Series.Add(seriesName);
                    series.CustomProperties = "DrawingStyle=Cylinder";
                    series.Legend = legendName;
                    series.XValueType = ChartValueType.DateTime;                 
                    
                    //add each returned value to series with appropriate tooltip
                    foreach (var reading in data)
                    {
                        double[] convertedReading = { Convert.ToDouble(reading.TotalKWh) };
                        var dateString = reading.HourDate.ToString("htt dd mmm yyyy");
                        var dateTooltip = string.Format("{0}: {1}, {2:0.0000} kWh", meter.me_meterName, dateString, reading.TotalKWh);
                        //var url = string.Format("MeterDaily.aspx?meterId={0}&monthStart={1}", meterId, dateUrl);
                        var newDataPointItem = new DataPoint {XValue=reading.HourDate.ToOADate(), YValues = convertedReading,  ToolTip = dateTooltip };
                        series.Points.Add(newDataPointItem);

                    }
                    //set new series location and type
                    series.ChartArea = "ChartArea1";
                    series.ChartType = SeriesChartType.StackedColumn;
                    series.BorderWidth = 2;
                }



            }
        }
    }
}
